package com.gxa.service.impl;

import com.github.pagehelper.PageInfo;
import com.gxa.dto.ResultData;
import com.gxa.exception.DataException;
import com.gxa.mapper.GoodsMapper;
import com.gxa.mapper.GoodsTypeMapper;
import com.gxa.pojo.GoodsType;
import com.gxa.pojo.GoodsTypeExample;
import com.gxa.service.GoodsTypeService;
import com.gxa.utils.MyValidator;
import com.gxa.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:IT-CNLM
 * @date:Created at 2020/07/27
 */
@Service
public class GoodsTypeServiceImpl implements GoodsTypeService {

    @Autowired
    private GoodsTypeMapper goodsTypeMapper;


    /**
     * 类型列表
     * @return
     */
    @Override
    public ResultData list() {
        ResultData<Map> resultData = new ResultData<>();
        List<Map<String, Object>> goodsTypeList;
        goodsTypeList = goodsTypeMapper.listType();
        PageInfo<Map<String, Object>> pages = new PageInfo<>(goodsTypeList, 3);
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", pages.getTotal());
        map.put("pages", pages.getPages());
        map.put("pagenum", pages.getPageNum());
        map.put("list", pages.getList());

        resultData.setCode(200);
        resultData.setData(map);
        return resultData;
    }

    /**
     * 添加
     * @param goodsType
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData add(GoodsType goodsType) {

        if(StringUtil.isEmpty(goodsType.getName())){
            throw  new DataException(1001,"分类名不能为空!");
        }
        GoodsTypeExample goodsTypeExample = new GoodsTypeExample();
        goodsTypeExample.createCriteria().andNameEqualTo(goodsType.getName());
        long count = goodsTypeMapper.countByExample(goodsTypeExample);
        if(count > 0){
            throw new DataException(1002, "分类名不能重复!");
        }
        goodsTypeMapper.insertSelective(goodsType);

        return new ResultData(200,"添加成功!");
    }

    /**
     * 编辑商品
     * @param goodsType
     * @return
     */
    @Override
    public ResultData edit(GoodsType goodsType) {

        goodsTypeMapper.updateByPrimaryKeySelective(goodsType);

        return new ResultData(200,"更新成功");
    }

    /**
     * 删除商品
     * @param id
     * @return
     */
    @Override
    public ResultData delete(Integer id) {
        goodsTypeMapper.deleteByPrimaryKey(id);
        return new ResultData(200, "删除成功");
    }
}
